package com.ikangtai.shecare.record;

import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.CameraSurfaceView;
import com.ikangtai.shecare.common.baseView.MaskView;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.RecordInfo;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.DisplayUtil;
import com.ikangtai.shecare.common.util.PxDxUtil;
import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class HCGCameraActivity extends BaseActivity implements CameraInterface.CamOpenOverCallback {
    CameraSurfaceView surfaceView = null;
    ImageButton shutterBtn;
    Button confirmButton;
    Button retakeButton;
    MaskView maskView = null;
    float previewRate = -1f;
    int DST_CENTER_RECT_WIDTH = 300; //单位是dip
    int DST_CENTER_RECT_HEIGHT = 80;//单位是dip
    Point rectPictureSize = null;
    private DBManager dbManager;
    private DateUtil dateUtil = new DateUtil();
    private String picNameID = null;
    int photoFlag = 0;
    private String date;
    private int result;
    List<RecordInfo> HCGList = new ArrayList<RecordInfo>();
    private TopBar topBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_hcg_camera);
        initUI();
        initViewParams();
        StatusBarUtil.setColor(this, getResources().getColor(R.color.early_pregnancy_color), 0);

        initView();

        Intent intent = getIntent();
        result = intent.getIntExtra("result", 0);
        date = intent.getStringExtra("date");

        dbManager = new DBManager(this);

        new Handler().postDelayed(new Runnable() {

            public void run() {
                CameraInterface.getInstance().doStopCamera();
                CameraInterface.getInstance().doOpenCamera(HCGCameraActivity.this);
            }

        }, 200);
        shutterBtn.setOnClickListener(new BtnListeners());
        confirmButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                HCGList = dbManager.getRecordHCG(date.substring(0, 10), "HCGPaperID");
                if (HCGList.size() > 0) {
                    for (int i = 0; i < HCGList.size(); i++) {
                        if (HCGList.get(i).getHCGIsDelete() == 0 && HCGList.get(i).getHCGIsSynced() == 0) {
                            dbManager.updateRecordHCG(HCGList.get(i).getHCGPaperID(), 1, 0);
                        }
                    }
                }
                dbManager.insertRecordHCG(App.userName, date, picNameID, result, 0, 0);
                Intent intent = new Intent();
                intent.putExtra("photoAddress", " ");
                intent.putExtra("picNameID", picNameID);
                intent.putExtra("picNameDate", date);
                setResult(5, intent);
                finish();
            }
        });

        retakeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraInterface.getInstance().doStopCamera();
                new Handler().postDelayed(new Runnable() {

                    public void run() {

                        CameraInterface.getInstance().doOpenCamera(HCGCameraActivity.this);
                    }

                }, 200);
                confirmButton.setVisibility(View.GONE);
                retakeButton.setVisibility(View.GONE);
                shutterBtn.setVisibility(View.VISIBLE);
                shutterBtn.setOnClickListener(new BtnListeners());

            }
        });
    }

    private final void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {
            }

            @Override
            public void midRightClick() {
            }

            @Override
            public void rightClick() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        CameraInterface.getInstance().doStopCamera();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        return true;
    }

    private void initUI() {
        surfaceView = (CameraSurfaceView) findViewById(R.id.camera_surfaceview);
        shutterBtn = (ImageButton) findViewById(R.id.btn_shutter);
        maskView = (MaskView) findViewById(R.id.view_mask);
        confirmButton = (Button) findViewById(R.id.camera_result_deal_onfirm);
        retakeButton = (Button) findViewById(R.id.camera_result_deal_retake);
        confirmButton.setVisibility(View.GONE);
        retakeButton.setVisibility(View.GONE);
    }

    private void initViewParams() {
        LayoutParams params = surfaceView.getLayoutParams();
        Point p = DisplayUtil.getScreenMetrics(this);
        params.width = p.x;
        params.height = p.y;
        previewRate = DisplayUtil.getScreenRate(this); //默认全屏的比例预览
        surfaceView.setLayoutParams(params);

        //手动设置拍照ImageButton的大小为120dip×120dip,原图片大小是64×64
        LayoutParams p2 = shutterBtn.getLayoutParams();
        p2.width = PxDxUtil.dip2px(this, 80);
        p2.height = PxDxUtil.dip2px(this, 80);
        shutterBtn.setLayoutParams(p2);

    }

    @Override
    public void cameraHasOpened() {
        // TODO Auto-generated method stub
        SurfaceHolder holder = surfaceView.getSurfaceHolder();
        CameraInterface.getInstance().doStartPreview(holder, previewRate);
        if (maskView != null) {
            Rect screenCenterRect = createCenterScreenRect(PxDxUtil.dip2px(this, DST_CENTER_RECT_WIDTH)
                    , PxDxUtil.dip2px(this, DST_CENTER_RECT_HEIGHT));
            maskView.setCenterRect(screenCenterRect);
        }
    }

    private class BtnListeners implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_shutter:
                    try {
                        if (rectPictureSize == null) {
                            rectPictureSize = createCenterPictureRect(PxDxUtil.dip2px(HCGCameraActivity.this, DST_CENTER_RECT_WIDTH)
                                    , PxDxUtil.dip2px(HCGCameraActivity.this, DST_CENTER_RECT_HEIGHT));
                        }
                        picNameID = UUID.randomUUID().toString();
                        CameraInterface.getInstance().doTakePicture(rectPictureSize.x, rectPictureSize.y, picNameID);
                        confirmButton.setVisibility(View.VISIBLE);
                        retakeButton.setVisibility(View.VISIBLE);
                        shutterBtn.setVisibility(View.GONE);
                    } catch (Exception e) {
                        AppLog.i("take photo e : " + e);
                    }
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 生成拍照后图片的中间矩形的宽度和高度
     *
     * @param w 屏幕上的矩形宽度，单位px
     * @param h 屏幕上的矩形高度，单位px
     * @return
     */
    private Point createCenterPictureRect(int w, int h) {

        int wScreen = DisplayUtil.getScreenMetrics(this).x;
        int hScreen = DisplayUtil.getScreenMetrics(this).y;
        int wSavePicture = CameraInterface.getInstance().doGetPrictureSize().y;
        int hSavePicture = CameraInterface.getInstance().doGetPrictureSize().x;
        float wRate = (float) (wSavePicture) / (float) (wScreen);
        float hRate = (float) (hSavePicture) / (float) (hScreen);
        float rate = (wRate <= hRate) ? wRate : hRate;//也可以按照最小比率计算

        int wRectPicture = (int) (w * wRate);
        int hRectPicture = (int) (h * hRate);
        return new Point(wRectPicture, hRectPicture);

    }

    /**
     * 生成屏幕中间的矩形
     *
     * @param w 目标矩形的宽度,单位px
     * @param h 目标矩形的高度,单位px
     * @return
     */
    private Rect createCenterScreenRect(int w, int h) {
        int x1 = DisplayUtil.getScreenMetrics(this).x / 2 - w / 2;
        int y1 = DisplayUtil.getScreenMetrics(this).y / 2 - h / 2;
        int x2 = x1 + w;
        int y2 = y1 + h;
        return new Rect(x1, y1, x2, y2);
    }

}
